# -*- coding:UTF-8 -*-
import decimal
import random
import time
import traceback

from db import *
from spider_xue.logger import logging
from spider_xue.new_ip import new_ip_obj, headers_list
from spider_xue.settings import ERROR, INFO, NINE_TIME_STAMP, URL5, URLDAY, KEYS
from spider_xue.spider import Snowball
from spider_xue.utils import EMA, send_msg


def do_day(account, stocks, workQueueIP):
    snow = Snowball(set_stock_tmp)
    flag, iipp = snow.refresh_session_queue(account['cookies'], workQueueIP)
    if not flag:
        return stocks
    fail = []
    tt = int(time.time())
    start = str(tt + 3600) + "000"
    end = '1000'
    i = 0
    nine = settings_db.find_one({"name": 'nine_timestamp'})
    for i in range(len(stocks)):
        try:
            flag = snow.get_res_together(
                URLDAY, stocks[i], start, end, data_day_db, nine['timestamp'])
            # flag = snow.get_res_5(stocks[i]['symbol'], start, end)
            time.sleep(0.5)
            if not flag:
                fail.append(stocks[i])
        except Exception as e:
            err = str(e) if 'HTTPConnectionPool' not in str(
                e) else "HTTPConnectionPool problem"
            logging.error(
                f"mission Exception {stocks[i]['symbol']} {err} --- use IP: {iipp} ")
            fail.append(stocks[i])
    return fail

# 检查是否涨停和跌停，两者都略过 0 涨停 1 跌停 2 ok


def set_today_status(x, timestamp):
    item = x['item']
    last = item[-1]
    # if last != -1:
    #     pass
    if last[7] > 9.8:
        stock_db.update({"symbol": x['symbol']}, {"$set": {"today": 0}})
    elif last[7] < -9.8:
        stock_db.update({"symbol": x['symbol']}, {"$set": {"today": 1}})
    else:
        stock_db.update({"symbol": x['symbol']}, {"$set": {"today": 2}})


# 检查是否涨停和跌停，两者都略过 0 涨停 1 跌停 2 ok
def set_stock_tmp(x, stock, timestamp):
    item = x['item']
    last = item[-1]
    # if last != -1:
    #     pass
    # for i in item:
    #     if i[0] == 1633622400000:
    #         last = i
    #         break

    if last[7] < -9:
        stock_db.update({"symbol": x['symbol']}, {
                        "$set": {"today": 1, 'end_price': last[5]}}, upsert=True)
    else:
        stock_db.update({"symbol": x['symbol']}, {
                        "$set": {"today": 2, 'end_price': last[5]}}, upsert=True)


def do_day_set_all(account, stocks, workQueueIP):
    snow = Snowball(set_all_stock_tmp)

    iipp = workQueueIP.get()
    snow.headers['user-agent'] = random.choice(headers_list)
    snow.headers['cookie'] = account['cookies']
    snow.session.headers = snow.headers
    snow.session.proxies = {"http": "http://{}".format(iipp["ip"])}

    fail = []
    tt = int(time.time())
    start = str(tt + 3600) + "000"
    end = '300'
    i = 0
    nine = settings_db.find_one({"name": 'nine_timestamp'})
    for i in range(len(stocks)):
        try:
            flag = snow.get_res_together(
                URLDAY, stocks[i], start, end, data_day_db, nine['timestamp'])
            time.sleep(0.5)
            if not flag:
                fail.append(stocks[i])
        except Exception as e:
            if 'HTTPConnectionPool' not in str(e):
                traceback.print_exc()
            err = str(e) if 'HTTPConnectionPool' not in str(
                e) else "HTTPConnectionPool problem"
            logging.error(
                f"mission Exception {stocks[i]['symbol']} {err} --- use IP: {iipp['ip']} ")
            # new_ip_obj.delete_one(iipp)
            return fail + stocks[i:]
    return fail


def set_all_stock_tmp(x, stock, timestamp):
    item = x['item']

    last = item[-1]
    # if last != -1:
    #     pass
    # for i in item:
    #     if i[0] == 1633622400000:
    #         last = i
    #         break

    if stock.get("use", 0):
        today = 0
        fuck = -3
        yesterday = 0
        byesterday = 0
        if last[7] > -6:
            if not stock.get('gsjj'):
                print(stock['symbol'], 11111111111111)
            msg = stock.get('gsjj', "") + stock.get('hxtc', '') + stock.get('ths_hxtc', '')
            f = 0
            for k in KEYS:
                if k in msg:
                    f = 1
                    break
            # f = 1
            if f:
                dd = data_day_db.find_one({"symbol": x['symbol']})
                ct1 = 0
                ct2 = 0
                ct3 = 0
                lasttt = 0
                today = 0
                fu_today = []
                for d in dd['item'][-10:]:
                    if d[7] < -6.2:
                        today = 16
                        
                    if d[7] < 2:
                        ct1 += 1

                    if d[7] < 1:
                        ct2 += 1

                    if d[7] < 0:
                        ct3 += 1

                    if d[7] < -1.5:
                        fu_today.append(d[7])
                    else:
                        fu_today = []

                    if len(fu_today) == 3:
                       today = 12

                    if lasttt + d[7] < -10:
                        today = 13

                    if lasttt + d[7] > 15:
                        today = 17
                
                    lasttt = d[7]
                    
                ppp = (dd['item'][-1][5] -  dd['item'][-10][2]) / dd['item'][-10][2] * 100
                if ppp > 15:
                        today = 14
                if ppp < -12:
                    today = 15
            
                if not today:
                    
                    if ct3 < 6:
                        today = 1

                    if ct2 < 6:
                        today = 2

                    if ct1 < 6:
                        today = 3

                    if ct3 < 6:
                        todays = EMA([round(decimal.Decimal(x[5]), 2)
                                    for x in dd['item']])
                        fuck = todays
                        if record_main_db.find_one({"symbol": x['symbol'], 'ts': timestamp-34200}):
                            yesterday = 1
                        if record_main_db.find_one({"symbol": x['symbol'], 'ts': timestamp-120600}):
                            byesterday = 1
                    if today > 0:
                        if dd['item'][-2][5] - dd['item'][-2][2] >= 0 and dd['item'][-1][5] - dd['item'][-1][2] >= 0 and dd['item'][-3][5] - dd['item'][-3][2] >= 0:
                            if 0 < dd['item'][-2][7] < 2:
                                if dd['item'][-1][7] >= 0:
                                    today = 4
                            if dd['item'][-2][7] > 1.5 and dd['item'][-1][7] >= dd['item'][-2][7]:
                                today = 4
            else:
                today = 11
        else:
            today = 10
        stock_db.update({"symbol": x['symbol']}, {
                        "$set": {"today": today, 'end_price': last[5], 'macd': fuck, 
                        'liang': last[9], 'yesterday': yesterday, 'byesterday': byesterday}}, upsert=True)
